<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>使用angular实现页面的注册</title>
  <!--  引入angular技术文件-->

<script type="text/javascript" src="./node_modules/angular/angular.js"></script>

</head>
<body ng-app="myApp">
  <table ng-controller ="registerController">
    <tr>
       <td>
         用户名:
         <input type="text" ng-model="username">
       </td>
    </tr>
    <tr><td> 用户类型:<select ng-model="usertype">
      <option value="student">学生</option>
      <option value="teacher">老师</option>
      <option value="admin">管理员</option>
    </select></td></tr>
    <tr>
      <td> 密码:<input type="password" ng-model="password"></td>
    </tr>
    <tr>
      <td>确认密码:<input type="password" ng-model="refirmpwd"></td>
    </tr>
    <tr><td>是否同意该协议<input type="checkbox" ng-model="isagree"></td></tr>
    <tr>
      <td><input type="button" value="注册" ng-click="register()"></td>
    </tr>
    <tr>
      <td>{{msg}}</td>
    </tr>
  </table>
  <script type="text/javascript">
    //创建模块

    var app =angular.module("myApp",[]);
    //创建控制器
    app.controller("registerController",function($scope){
      //初始化数据模型
      $scope.username="";
      $scope.usertype="";
      $scope.password ="";
      $scope.refirmpwd="";
      $scope.isagree="";
      $scope.msg="";
      //初始化行为模型
      $scope.register= function(){
        if($scope.username.length<6){
           $scope.msg="用户名太短了!";
           return;
        }
        if($scope.password.length<6){
          $scope.password="密码不能小于6位";
          return;
        }
        if($scope.password !== $scope.refirmpwd){
          $scope.msg="两次输入的密码不相同,请重新输入!!!";
          return;
        }
        var u = new User($scope.username,$scope.password,$scope.usertype);
        var result =u.save();
        if(result){
          $scope.msg="注册成功";
        }else{
          $scope.msg="注册失败";
        }
      }
      //创建一个构造函数
      function User(name,pwd,type){
        this.name=name;
        this.pwd=pwd;
        this.type=type;
      }
      User.prototype.save=function(){
        var str =localStorage.getItem("myusers")|| '[]';
        var arr =JSON.parse(str);
        for(var i=0;i<arr.length;i++){
          if(arr[i].name === this.name){
             return false;
          }
        }
        arr.push({name:this.name,pwd:this.pwd,type:this.type});
        localStorage.setItem("myusers",JSON.stringify(arr));
        return true;
      }

    });

  </script>
</body>
</html>
